package com.github.baichuan.application.dashboard.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.baichuan.web.security.JwtCodec;
import lombok.Builder;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Value;

import java.util.Arrays;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;

@Builder
public class Jwt implements JwtCodec<Principal> {
    /**
     * token存活时间(分钟)
     */
    @Value("${security.jwt.ttl}")
    private int ttl;

    private Algorithm algorithm;

    public String encode(@NonNull Principal principal){
        Set<String> authorizations = principal.getAuthorizations();

        String token = JWT.create().withClaim("uid", principal.getUid())
                .withClaim("name", principal.getName())
                .withClaim("memberType", principal.getMemberType().toString())
//                .withClaim("tenant", principal.getTenant())
                .withClaim("orgBranch", principal.getOrgBranch())
                .withArrayClaim("authorizations", authorizations.toArray(new String[authorizations.size()]))
                .withExpiresAt(new Date(System.currentTimeMillis() + this.ttl * 60000))
                .sign(algorithm);
        return token;
    }

    public Principal decode(String token){
        DecodedJWT jwt = JWT.require(algorithm).build().verify(token);
        Principal.PrincipalBuilder builder = Principal.builder();
        builder.uid(jwt.getClaim("uid").asString());
        builder.name(jwt.getClaim("name").asString());
        builder.memberType(jwt.getClaim("memberType").asString());
//        builder.tenant(jwt.getClaim("tenant").asString());
        builder.orgBranch(jwt.getClaim("orgBranch").asString());
        builder.authorizations(Arrays.stream(jwt.getClaim("authorizations").asArray(String.class)).collect(Collectors.toSet()));
        return builder.build();
    }
}
